package com.carbeauty.controller;

import com.carbeauty.entity.Customer;
import com.carbeauty.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 客户管理控制器
 * 
 * 功能说明:
 * - 客户信息的增删改查
 * - 客户列表展示和搜索
 * - 客户详情查看
 * - 会员管理功能
 * - 余额和积分管理
 * 
 * 权限要求:
 * - 管理员、店长、员工可以访问客户管理功能
 * - 客户只能查看自己的信息
 * 
 * @author CarBeauty Team
 */
@Controller
@RequestMapping("/customers")
public class CustomerController {
    
    @Autowired
    private CustomerService customerService;
    
    // ==================== 页面控制器 ====================
    
    /**
     * 客户列表页面
     */
    @GetMapping
    public String list(Model model,
                      @RequestParam(defaultValue = "0") int page,
                      @RequestParam(defaultValue = "10") int size,
                      @RequestParam(required = false) String name,
                      @RequestParam(required = false) String phone,
                      @RequestParam(required = false) String carNumber,
                      @RequestParam(required = false) String memberLevel) {
        
        Pageable pageable = PageRequest.of(page, size);
        Page<Customer> customers;
        
        // 根据搜索条件查询
        if (hasSearchParams(name, phone, carNumber, memberLevel)) {
            customers = customerService.searchCustomers(name, phone, carNumber, memberLevel, pageable);
        } else {
            customers = customerService.findAllActive(pageable);
        }
        
        model.addAttribute("customers", customers);
        model.addAttribute("searchName", name);
        model.addAttribute("searchPhone", phone);
        model.addAttribute("searchCarNumber", carNumber);
        model.addAttribute("searchMemberLevel", memberLevel);
        
        // 添加会员等级选项
        model.addAttribute("memberLevels", getMemberLevels());
        
        return "customers/list";
    }
    
    /**
     * 客户详情页面
     */
    @GetMapping("/{id}")
    public String detail(@PathVariable Long id, Model model) {
        Optional<Customer> customer = customerService.findById(id);
        if (customer.isPresent()) {
            model.addAttribute("customer", customer.get());
            return "customers/detail";
        } else {
            model.addAttribute("error", "客户不存在");
            return "error/404";
        }
    }
    
    /**
     * 新增客户页面
     */
    @GetMapping("/new")
    public String newCustomer(Model model) {
        model.addAttribute("customer", new Customer());
        model.addAttribute("memberLevels", getMemberLevels());
        model.addAttribute("carBrands", getCarBrands());
        model.addAttribute("carColors", getCarColors());
        model.addAttribute("customerSources", getCustomerSources());
        return "customers/form";
    }
    
    /**
     * 编辑客户页面
     */
    @GetMapping("/{id}/edit")
    public String edit(@PathVariable Long id, Model model) {
        Optional<Customer> customer = customerService.findById(id);
        if (customer.isPresent()) {
            model.addAttribute("customer", customer.get());
            model.addAttribute("memberLevels", getMemberLevels());
            model.addAttribute("carBrands", getCarBrands());
            model.addAttribute("carColors", getCarColors());
            model.addAttribute("customerSources", getCustomerSources());
            return "customers/form";
        } else {
            model.addAttribute("error", "客户不存在");
            return "error/404";
        }
    }
    
    // ==================== API接口 ====================
    
    /**
     * 保存客户信息
     */
    @PostMapping
    public String save(@Valid @ModelAttribute Customer customer, 
                      BindingResult result, Model model) {
        
        // 验证表单数据
        if (result.hasErrors()) {
            model.addAttribute("customer", customer);
            model.addAttribute("memberLevels", getMemberLevels());
            model.addAttribute("carBrands", getCarBrands());
            model.addAttribute("carColors", getCarColors());
            model.addAttribute("customerSources", getCustomerSources());
            return "customers/form";
        }
        
        // 验证手机号是否重复
        if (customerService.isPhoneExists(customer.getPhone(), customer.getId())) {
            result.rejectValue("phone", "duplicate", "手机号已存在");
            model.addAttribute("customer", customer);
            return "customers/form";
        }
        
        try {
            customerService.save(customer);
            return "redirect:/customers?success=true";
        } catch (Exception e) {
            model.addAttribute("error", "保存失败: " + e.getMessage());
            model.addAttribute("customer", customer);
            return "customers/form";
        }
    }
    
    /**
     * 删除客户
     */
    @PostMapping("/{id}/delete")
    public String delete(@PathVariable Long id) {
        try {
            customerService.deleteById(id);
            return "redirect:/customers?deleted=true";
        } catch (Exception e) {
            return "redirect:/customers?error=" + e.getMessage();
        }
    }
    
    /**
     * 批量删除客户
     */
    @PostMapping("/batch-delete")
    public String batchDelete(@RequestParam List<Long> ids) {
        try {
            customerService.deleteByIds(ids);
            return "redirect:/customers?deleted=true";
        } catch (Exception e) {
            return "redirect:/customers?error=" + e.getMessage();
        }
    }
    
    // ==================== AJAX API ====================
    
    /**
     * 获取客户信息（AJAX）
     */
    @GetMapping("/{id}/json")
    @ResponseBody
    public ResponseEntity<Customer> getCustomerJson(@PathVariable Long id) {
        Optional<Customer> customer = customerService.findById(id);
        return customer.map(ResponseEntity::ok)
                      .orElse(ResponseEntity.notFound().build());
    }
    
    /**
     * 根据手机号查找客户（AJAX）
     */
    @GetMapping("/search/phone")
    @ResponseBody
    public ResponseEntity<Customer> findByPhone(@RequestParam String phone) {
        Optional<Customer> customer = customerService.findByPhone(phone);
        return customer.map(ResponseEntity::ok)
                      .orElse(ResponseEntity.notFound().build());
    }
    
    /**
     * 根据会员卡号查找客户（AJAX）
     */
    @GetMapping("/search/card")
    @ResponseBody
    public ResponseEntity<Customer> findByCardNo(@RequestParam String cardNo) {
        Optional<Customer> customer = customerService.findByCardNo(cardNo);
        return customer.map(ResponseEntity::ok)
                      .orElse(ResponseEntity.notFound().build());
    }
    
    /**
     * 客户充值（AJAX）
     */
    @PostMapping("/{id}/recharge")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> recharge(@PathVariable Long id,
                                                       @RequestParam BigDecimal amount,
                                                       @RequestParam(required = false) BigDecimal bonusAmount,
                                                       @RequestParam String paymentMethod) {
        Map<String, Object> result = new HashMap<>();
        try {
            // TODO: 获取当前操作员ID
            Long operatorId = 1L; // 临时使用固定值
            
            Customer customer = customerService.recharge(id, amount, bonusAmount, operatorId, paymentMethod);
            result.put("success", true);
            result.put("message", "充值成功");
            result.put("customer", customer);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "充值失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }
    
    /**
     * 客户消费（AJAX）
     */
    @PostMapping("/{id}/consume")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> consume(@PathVariable Long id,
                                                      @RequestParam BigDecimal amount) {
        Map<String, Object> result = new HashMap<>();
        try {
            Customer customer = customerService.consume(id, amount);
            result.put("success", true);
            result.put("message", "消费成功");
            result.put("customer", customer);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "消费失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }
    
    /**
     * 验证手机号是否存在（AJAX）
     */
    @GetMapping("/validate/phone")
    @ResponseBody
    public ResponseEntity<Map<String, Boolean>> validatePhone(@RequestParam String phone,
                                                             @RequestParam(required = false) Long excludeId) {
        boolean exists = customerService.isPhoneExists(phone, excludeId);
        Map<String, Boolean> result = new HashMap<>();
        result.put("exists", exists);
        return ResponseEntity.ok(result);
    }
    
    // ==================== 辅助方法 ====================
    
    /**
     * 检查是否有搜索参数
     */
    private boolean hasSearchParams(String name, String phone, String carNumber, String memberLevel) {
        return (name != null && !name.trim().isEmpty()) ||
               (phone != null && !phone.trim().isEmpty()) ||
               (carNumber != null && !carNumber.trim().isEmpty()) ||
               (memberLevel != null && !memberLevel.trim().isEmpty());
    }
    
    /**
     * 获取会员等级选项
     */
    private List<String> getMemberLevels() {
        return List.of("普通会员", "铜卡会员", "银卡会员", "黄金会员", "钻石会员");
    }
    
    /**
     * 获取车辆品牌选项
     */
    private List<String> getCarBrands() {
        return List.of("丰田", "本田", "日产", "大众", "宝马", "奔驰", "奥迪", "其他品牌");
    }
    
    /**
     * 获取车辆颜色选项
     */
    private List<String> getCarColors() {
        return List.of("白色", "黑色", "银色", "灰色", "红色", "蓝色", "其他颜色");
    }
    
    /**
     * 获取客户来源选项
     */
    private List<String> getCustomerSources() {
        return List.of("自然进店", "朋友推荐", "网络推广", "活动推广", "其他渠道");
    }
}
